package com.pengpeng.jjwt.common.handler;

import com.pengpeng.jjwt.common.exception.CustomException;
import com.pengpeng.jjwt.common.result.Result;
import com.pengpeng.jjwt.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


/**
 * @author pengp
 * @date 2022年03月03日 16:26
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义错误
     * @Author pengp
     * @Date 2022/3/3 16:28
     * @param e
     * @return com.pengpeng.jjwt.common.result.Result
     */
    @ExceptionHandler(CustomException.class)
    public Result handleException(CustomException e){
        log.error("#### 异常信息:{} ######",e.getMessage());
        return new Result(e.getResultCode());
    }
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Result handleException(Exception e){
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            BindingResult result = validException.getBindingResult();
            StringBuffer errorMsg = new StringBuffer();
            if(result.hasErrors()){
                List<ObjectError> errors = result.getAllErrors();
                errors.forEach(p ->{
                    FieldError fieldError = (FieldError) p;
                    errorMsg.append(fieldError.getDefaultMessage()).append(",");
                    log.error("#### 请求参数错误:{"+fieldError.getObjectName()+"},field:{"+fieldError.getField()+"},errorMessage:{"+fieldError.getDefaultMessage()+"}");
                });
            }else if(e instanceof BindException){
                log.error("#### 请求参数错误：---");
            }
        }
        return new Result(ResultCode.PARAM_IS_INVALID);
    }
    @ExceptionHandler(Exception.class)
    public Result handleOtherException(Exception e){
        e.printStackTrace();
        log.error("### 未知异常:{}  ###",e.getMessage());
        return new Result(ResultCode.SYSTEM_INNER_ERROR);
    }

}
